<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="应用名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入应用名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="标题" prop="titleName">
            <el-input v-model="queryParams.titleName" placeholder="请输入标题" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="简称" prop="shortName">
            <el-input v-model="queryParams.shortName" placeholder="请输入简称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="表名" prop="tableName">
            <el-input v-model="queryParams.tableName" placeholder="请输入表名" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="表主键" prop="tableId">
            <el-input v-model="queryParams.tableId" placeholder="请输入表主键" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:sheet:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Plus" @click="toSheetDiy()" v-hasPermi="['system:sheetField:add']">应用设计</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        v-loading="loading"
        :data="sheetList"
        row-key="sheetId"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        ref="sheetTableRef"
        :default-expand-all="isExpandAll"
        highlight-current-row
        @row-click="rowClick"
      >
        <el-table-column label="应用名称" align="center" prop="name" />
        <el-table-column label="主键ID" align="center" prop="sheetId" width="200" />
        <el-table-column label="父级ID" align="center" prop="pid" width="200" />
        <el-table-column label="标题" align="center" prop="titleName" />
        <el-table-column label="简称" align="center" prop="shortName" />
        <el-table-column label="表名" align="center" prop="tableName" />
        <el-table-column label="表主键" align="center" prop="tableId" />
        <el-table-column label="主表关联字段" align="center" prop="parentName" />
        <el-table-column label="是否启用" prop="status"  width="80">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="是否树表" prop="isTree"  width="80">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.isTree" />
          </template>
        </el-table-column>
        <el-table-column label="左固定列" align="center" prop="leftFixedIndex" />
        <el-table-column label="右固定列" align="center" prop="rightFixedIndex" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:sheet:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:sheet:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

    </el-card>
    <!-- 添加或修改应用对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="sheetFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="上级应用" prop="pid">
          <el-tree-select
            v-model="form.pid"
            :data="sheetOptions"
            :props="{ value: 'sheetId', label: 'name', children: 'children' }"
            :filter-node-method="filterNodeMethod"
            value-key="sheetId"
            placeholder="选择上级应用"
            check-strictly
            filterable
          />
        </el-form-item>
        <el-form-item label="应用名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入应用名称" />
        </el-form-item>
        <el-form-item label="标题" prop="titleName">
          <el-input v-model="form.titleName" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="简称" prop="shortName">
          <el-input v-model="form.shortName" placeholder="请输入简称" />
        </el-form-item>
        <el-form-item label="表名" prop="tableName">
          <el-input :disabled="form.sheetId===undefined?false:true" v-model="form.tableName" placeholder="请输入表名" />
        </el-form-item>
        <el-form-item label="表主键" prop="tableId">
          <el-input v-model="form.tableId" placeholder="请输入表主键" />
        </el-form-item>
        <el-form-item label="主表关联字段" prop="parentName" v-if="form.pid !==0">
          <el-input v-model="form.parentName" placeholder="请输入主表关联字段" />
        </el-form-item>
        <el-form-item label="数据源">
          <el-form-item label="数据字典" >
            <el-select v-model="form.dictId" multiple clearable filterable placeholder="请选择">
              <el-option v-for="dict in dictOptions" :key="dict.dictType" :label="dict.dictName" :value="dict.dictId">
                <span style="float: left">{{ dict.dictName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictType }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="自定义源" style="margin-top: 20px;">
            <el-select v-model="form.sourceId" multiple clearable filterable placeholder="请选择">
              <el-option v-for="dataSource in dataSourceList" :key="dataSource.dataSourceId" :label="dataSource.name" :value="dataSource.dataSourceId">
                <span style="float: left">{{ dataSource.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ dataSource.tableName }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否树表" prop="isTree">
          <el-radio-group v-model="form.isTree">
            <el-radio
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="左固定列" prop="leftFixedIndex">
          <el-input-number v-model="form.leftFixedIndex" :min="1" style="width: 200px" placeholder="请输入左固定列" />
        </el-form-item>
        <el-form-item label="右固定列" prop="rightFixedIndex">
          <el-input-number v-model="form.rightFixedIndex" :min="1" style="width: 200px" placeholder="请输入右固定列" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Sheet" lang="ts">
import { listSheet, getSheet, delSheet, addSheet, updateSheet, listSheetAll } from '@/api/sheet/sheet';
import { SheetVO, SheetQuery, SheetForm } from '@/api/sheet/sheet/types';
import {checkTableName, checkTableField, listDataSource} from '@/api/sheet/dataSource';
import { optionselect } from '@/api/system/dict/type';
import {DictTypeVO} from "@/api/system/dict/type/types";
import { listAllDataSource } from '@/api/sheet/dataSource';
import {DataSourceQuery, DataSourceVO} from "@/api/sheet/dataSource/types";

const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { sys_yes_no } = toRefs<any>(proxy?.useDict( "sys_yes_no"));


const sheetList = ref<SheetVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const isExpandAll = ref(false)

const queryFormRef = ref<ElFormInstance>();
const sheetFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
});

const initFormData: SheetForm = {
  sheetId: undefined,
  pid: undefined,
  name: undefined,
  titleName: undefined,
  shortName: undefined,
  tableName: undefined,
  tableId: undefined,
  parentName: undefined,
  status: 'Y',
  dictId: undefined,
  sourceId: undefined,
  leftFixedIndex: undefined,
  rightFixedIndex: undefined,
  remark: undefined,
  isTree: 'N'
}

const dictOptions = ref<DictTypeVO[]>([]);

const sheetId = ref<any>("");

/**
 * 校验数据源表名
 * @param rule
 * @param value
 * @param callback
 */
const validateTableName = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('数据源表名称不能为空'))
  } else {
    if (form.value.tableName !== '') {
      checkTableName(form.value.tableName).then(res =>{
        if (res.data == 0){
          callback(new Error('未查询到该表名'))
        } else {
          callback()
        }
      });
    } else {
      callback()
    }
  }
}

/**
 * 表字段校验
 * @param rule
 * @param value
 * @param callback
 */
const validateTableId = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('数据源表ID不能为空'))
  } else {
    if (form.value.tableName == '' || form.value.tableName == undefined) {
      callback(new Error('请先输入表名'))
    } else {
      setTimeout(() => {
        checkTableField(form.value.tableName, value).then(res =>{
          if (res.data == 0){
            callback(new Error('该表中没有此字段'))
          } else {
            callback()
          }
        });
      }, 600)
    }
  }
}

const data = reactive<PageData<SheetForm, SheetQuery>>({
  form: {...initFormData},
  queryParams: {
    pid: undefined,
    name: undefined,
    titleName: undefined,
    shortName: undefined,
    tableName: undefined,
    tableId: undefined,
    leftFixedIndex: undefined,
    rightFixedIndex: undefined,
    remark: undefined,
    params: {}
  },
  rules: {
    name: [
      { required: true, message: "应用名称不能为空", trigger: "blur" }
    ],
    tableName: [
      { required: true, message: "表名称不能为空", trigger: "blur" },
      { max: 50, message: '长度不能超过50个字符', trigger: 'blur' },
      { validator: validateTableName, trigger: 'blur' }
    ],
    tableId: [
      { required: true, message: "表ID不能为空", trigger: "blur" },
      { max: 50, message: '长度不能超过50个字符', trigger: 'blur' },
      { validator: validateTableId, trigger: 'blur' }
    ],
    parentName: [
      { required: true, message: "主表关联字段不能为空", trigger: "blur" },
      { max: 50, message: '长度不能超过50个字符', trigger: 'blur' },
    ],
  }
});

const sheetTableRef = ref<ElTableInstance>();

const { queryParams, form, rules } = toRefs(data);

interface SheetOptionsType {
  sheetId: number | string;
  name: string;
  children: SheetOptionsType[] | undefined;
}

const sheetOptions = ref<SheetOptionsType[]>([])

const filterNodeMethod = (value : string | number, data: any) => data.name.includes(value)

const dataSourceList = ref<DataSourceVO[]>([]);

const queryDataSourceParams = reactive<DataSourceQuery>({
  status: "Y",
  pageNum: 0,
  pageSize: 0
})


/** 查询应用列表 */
const getList = async () => {
  loading.value = true
  const res = await listSheet(queryParams.value);
  const data = proxy?.handleTree<SheetVO>(res.data, "sheetId", "pid")
  if (data) {
    sheetList.value = data
  }
  loading.value = false
}

/** 查询应用下拉树结构 */
const getTreeselect = async () => {
  sheetOptions.value = []
  const response = await listSheet();
  const sheet: SheetOptionsType = { sheetId: 0, name: "主类目", children: [] }
  sheet.children = proxy?.handleTree<SheetOptionsType>(response.data, "sheetId", "pid")
  sheetOptions.value.push(sheet)
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  sheetFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 新增按钮操作 */
const handleAdd = async (row?: SheetVO) => {
  reset();
  getTreeselect();
  row && row.sheetId ? form.value.pid = row.sheetId : form.value.pid = 0;
  dialog.visible = true;
  dialog.title = "添加应用";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: SheetVO) => {
  reset();
  await getTreeselect();
  if (row?.sheetId) {
    const { data } = await getSheet(row.sheetId);
    form.value = data;
    if (data.dictId){
      const arr = data.dictId.split(",");
      const newArr = [];
      for (const i in arr) {
        if (arr[i].length < 10){
          newArr.push(Number.parseInt(arr[i]))
        } else {
          newArr.push(arr[i])
        }
      }
      form.value.dictId = newArr;
    }
    if (data.sourceId){
      form.value.sourceId = data.sourceId.split(",");
    }
  }
  dialog.visible = true;
  dialog.title = "修改应用";
}

/** 提交按钮 */
const submitForm = () => {
  sheetFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.dictId){
        form.value.dictId = form.value.dictId.toString();
      }
      if (form.value.sourceId){
        form.value.sourceId = form.value.sourceId.toString();
      }
      if (form.value.sheetId) {
        await updateSheet(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        console.info(form.value)
        await addSheet(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: SheetVO) => {
  await proxy?.$modal.confirm('是否确认删除名称为"' + row?.name + '"的数据项?');
  await delSheet(row?.sheetId);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}


/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/sheet/export', {
    ...queryParams.value
  }, `sheet_${new Date().getTime()}.xlsx`)
}

/** 应用设计操作 */
const toSheetDiy = () => {
  router.push("/sheet/sheetField/index");
}

/** 获取自定义数据源 */
const getAllDataSourceList = async () => {
  const res = await listAllDataSource(queryDataSourceParams);
  dataSourceList.value = res.data;
}

/** 获取数据字典 */
const getDictOptionselect = async () => {
  const response = await optionselect();
  dictOptions.value = response.data;
}

/** 点击表格操作 */
const rowClick = (row?: SheetVO) => {
  sheetId.value = row?.sheetId;
}

onMounted(() => {
  getList();
  getAllDataSourceList();
  getDictOptionselect();
});
</script>
